package com.hjj.controller;

import com.hjj.beans.Activity;
import com.hjj.beans.User;
import com.hjj.dto.ResultDTO;
import com.hjj.dto.ResultPageDTO;
import com.hjj.exception.CRUDException;
import com.hjj.exception.LoginException;
import com.hjj.services.ActivityServices;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;

@RestController
@RequestMapping("/Activity")
public class ActivityController {
    @Autowired
    ActivityServices activityServices;

    @RequestMapping("getAll.action")
    public ResultPageDTO getAll(ResultPageDTO resultPageDTO){
        // 获取活动的所有数据
        ArrayList<Activity> all = activityServices.getAll(resultPageDTO);

        // 将获取到的活动数据添加到数据传输对象中
        resultPageDTO.setData(all);

        return resultPageDTO;
    }

    @RequestMapping("add.action")
    public ResultDTO add(Activity activity, HttpSession httpSession) throws LoginException, CRUDException {
        // 获取当前登录者
        User user = (User) httpSession.getAttribute("user");

        if (user == null) throw new LoginException("你还没有登录");

        // 添加创建者
        activity.setCreateBy(user.getName());

        boolean add = activityServices.add(activity);

        if (!add)throw new CRUDException("活动数据添加失败");

        ResultDTO resultDTO = new ResultDTO();
        resultDTO.setResult(ResultDTO.SUCCESS);
        return resultDTO;
    }

    @RequestMapping("getIdAndRemark.action")
    public Activity getIdAndRemark(String id){
        return activityServices.get(id);
    }


    @RequestMapping("editBefore.action")
    public Activity editBefore(String id){
        return activityServices.editBefore(id);
    }


    @RequestMapping("edit.action")
    public ResultDTO edit(Activity activity, HttpSession httpSession) throws LoginException, CRUDException {
        // 获取当前登录者
        User user = (User) httpSession.getAttribute("user");

        if (user == null) throw new LoginException("你还没有登录");

        // 添加创建者
        activity.setEditBy(user.getName());

        boolean edit = activityServices.edit(activity);

        if (!edit)throw new CRUDException("活动数据修改失败");

        ResultDTO resultDTO = new ResultDTO();
        resultDTO.setResult(ResultDTO.SUCCESS);
        return resultDTO;
    }

    @RequestMapping("del.action")
    public ResultDTO del(@RequestBody String[] ids) throws CRUDException {
        boolean del = activityServices.del(ids);

        if (!del) throw new CRUDException("活动数据删除失败");

        ResultDTO resultDTO = new ResultDTO();
        resultDTO.setResult(ResultDTO.SUCCESS);

        return resultDTO;

    }
}
